import React from 'react'
// ===================================================================== Temp
import SearchForm from '#cpt/temp/SearchForm'
import FormModal from '#cpt/temp/FormModal'
import Table from '#cpt/temp/Table'
import Controls from '#cpt/temp/Controls'
import Confirm from '#cpt/temp/Confirm'
import SpecCode from '#tp/specCode'
/* 修改相关操作说明 20211009  --耿琰 */
import Asks from '#tp/asks'
// ===================================================================== antd
// ===================================================================== global declare
const { $fn, $http, $Lazy } = window
// ===================================================================== private component
const Page 			= $Lazy.load(()=>import('#tp/page/page-container'))
const ImportFile 	= $Lazy.load(()=>import('#private/common/import'))
const $cache 		= $Lazy.file(()=>import('#private/cache-api'))
const $time 		= $Lazy.file(()=>import('@com/utils/time'))
const PatientDetail = $Lazy.state(()=>import('./cpt/patient-detail'))
const ImgEdit 		= $Lazy.state(()=>import('./cpt/img-edit'))
// ===================================================================== data
// 添加相关操作说明 20210927 耿琰   20211009 修改
const CheckedStatus = [{ name:'未审核', value:'0', tip:Asks.CheckedUnreviewed },{ name:'已审核', value:'1', tip:Asks.Audited }]
const BasicStatus = [{ name:'未审核', value:'0', tip:Asks.BasicUnreviewed },{ name:'已审核', value:'1', tip:Asks.Audited }]
const BoolStatus = [{ name:'是', value: '1', tip:Asks.ThirdPutaway }, { name:'否', value:'0' }]
const BoxStatus = [{ name:'是', value: '1', tip:Asks.ThirdHospital }, { name:'否', value:'0' }]
const auditStatus= [{ name:'全部', value:'99' },{ name:'待完善', value:'0' },{ name:'待审核', value:'1' },{ name:'审核通过', value:'2' },{ name:'已作废', value:'-3' }]
// ===================================================================== component
class Index extends React.Component{
	state = {
		data:[],
		pag: {},
		selectedKeys:[],
		selectedRows:[],
		img_url:'',	//查看图片的url
		imageVisible : false,	// 是否显示图片
		key:0,
		// 搜索表单列表
		forms: [
			{ label: '状态',		name: 'status',			type:'select',		data:auditStatus },
			{ label: '医院名称',		name: 'hospital_id',	type:'select',		loading:true,	onValue: ({rows})=>{ this.model.hosp_name=rows?.name } },
			{ label: '条码号',		name: 'spec_code',	onValue: ({value})=>{if(value.length > 12) this.model.spec_code = value.slice(0,12)},	outer:true,
				onPressEnter: value => {
					if(value){
						this.fetch().then((items)=>{
							if($fn.hasArray(items)){
								this.patientDetailRef.setValue(items[0].uuid,true)
							}
							this.model.spec_code = ''
							this.searchFormRef.setValue({'spec_code':''})
						})
					}
				},
			},
			{ label: '病人姓名',		name: 'patient_name' },
			{ label: '送检科室',		name: 'department_name' },
			{ label: '证件号',		name: 'card_no' },
			{ label: '标签类型',		name: 'tag',						type:'select',		loading:true, 	idStr:'code' },
			/* 增加 采样类型、自然项目、录入人、录入时间搜索条件 2021-7-26 2:02:04 --马婷 */
			{ label: '采样类型',		name: 'collect_type',				type:'select',		loading:true,	idStr:'code'},
			{ label: '自然项目',		name: 'parent_kind_id',				type:'select',		loading:true },
			{ label: '录入人',		name: 'operator_id',				type:'select',		loading:true,	onValue: ({rows})=>{ this.model.operator_name=rows?.name }},
			{ label: '录入时间',		names: ['created_at','end_at'], 	type:'date-range', 	loading:true,	name:'jz-time' },
			{ label: '接收日期',		names: ['start_date','end_date'], 	type:'date-range', 	loading:true,	name:'jz-time1' },
			{ label:' ', 			tag: '仅显示有图', name:'view_pic',	type: 'checkbox', 	colon:false },
		],
		// 文件导入表单
		formData: [
			{ label:'项目清单',		name: 'checked_spec', 		type: 'radio', 	full:true, 	value:'1', data:CheckedStatus},
			{ label:'基本资料',		name: 'checked_info', 		type: 'radio', 	full:true, 	value:'1', data:BasicStatus },
			{ label:'开启第三方上架',name: 'third_open_shelf', 	type: 'radio', 	full:true, 	value:'0', data:BoolStatus },
			{ label:'第三方医院',	name: 'third_hosp_id',		type:'select',	full:true,	loading:true },
			// 导入添加选择标本箱 2021-9-26  --马婷 
			{ label:'是否选择导入标箱',name: 'is_box_code', 	type: 'radio', 	full:true, 	value:'0', data:BoxStatus,
				onValue:({value,formData})=>{
					if (value === '1'){
						$fn.hideRows(formData,['box_id'], false)
					}else{
						$fn.hideRows(formData,['box_id'], true)
					}
					this.setState({formData})
				}
			},
			{ label: '标本箱号',		name: 'box_id',	full:true,	type: 'select',	hide:true,	loading:true, nameStr:'box_code'},
		],
		doubleEntryEnabled: 0
	}
	model = {}
	query = {}
	permissions = 1
	btn_power = { upimportinfo:1,importtest:1,batchaudit:1,exportInfo:1,fastentrycaseinfo:1,exporttmp:1,importInfo:1 }
	
	componentDidMount(){
		// 按钮添加权限 2022-07-05 17:15:24  --马婷
		const { ban_btn } = $fn.local('permissions')
		if($fn.hasArray(ban_btn)){
			if(ban_btn.includes('speccaseinfo.upimportinfo')){		// 更新基本资料导入
				this.btn_power.upimportinfo = 0
			}
			if(ban_btn.includes('speccaseinfo.importtest')){		// 导入到检测中心
				this.btn_power.importtest = 0
			}
			if(ban_btn.includes('speccaseinfo.batchaudit')){		// 批量审核
				this.btn_power.batchaudit = 0
			}
			if(ban_btn.includes('speccaseinfo.export')){		// 导出
				this.btn_power.exportInfo = 0
			}
			if(ban_btn.includes('speccaseinfo.fastentrycaseinfo')){		// 快捷录入
				this.btn_power.fastentrycaseinfo = 0
			}
			if(ban_btn.includes('speccaseinfo.exporttmp')){		// 下载导入模板
				this.btn_power.exporttmp = 0
			}
			if(ban_btn.includes('speccaseinfo.import')){		// 文件导入
				this.btn_power.importInfo = 0
			}
		}
		this.getSelect()
		$time.then(f=>{				 /* 添加默认录入时间 2021-8-13 --马婷 */
			const arr = f.duration['7-0-24']()
			this.resetModel = { created_at: arr[0], end_date: arr[1], 'jz-time':arr }
			this.model = $fn.copy(this.resetModel)
			// this.fetch()		/* 第一次进入页面不加载数据  2021-8-26  --马婷 */
		})
		// 双录入权限 2022-07-04 16:10:02  --马婷
		const { ban_field } = $fn.local('permissions')
		if($fn.hasArray(ban_field)){
			if(!ban_field.includes('speckind.first') && !ban_field.includes('speckind.second')){
				this.permissions = 'double'
			}else if(ban_field.includes('speckind.first')&&!ban_field.includes('speckind.second')){
				this.permissions = 'second'
			}else if(ban_field.includes('speckind.second')&&!ban_field.includes('speckind.first')){
				this.permissions = 'first'
			}else {
				this.permissions = 0
			}
		}else{
			this.permissions = 'double'
		}
		this.getDoubleEntry()	// 是否展示双录入
	}
	// 获取下拉数据
	getSelect = () => {
		const { forms, formData } = this.state
		
		$cache.then( async f => {
			// 医院
			const _data = await f.getCache({ api:'hospital' })
			$fn.setRow( forms, 'hospital_id', _data )
			$fn.setRow( formData, 'third_hosp_id', _data )
			// 标签类型
			$fn.setRow( forms, 'tag', await f.getDicCache({ code:69700 }) )
			// 采集类型
			const collectType = $fn.setRow( forms, 'collect_type', await f.getDicCache({ code:69000 }) )
			// 自然项目
			$fn.setRow(forms, 'parent_kind_id', await f.getCache({ api:'nature_project' } ) )
			// 录入人
			$fn.setRow( forms, 'operator_id', await f.getCache({ api:'employee' }) )
			
			collectType.map( v => v['value']=v.code )
			this.setState({ forms, formData, collectType })
		})
	}
	// 弹窗获取下拉数据
	getModalSelect = () => {
		const { formData } = this.state
		$cache.then( async f => {
			//标本箱号
			$fn.setRow( formData, 'box_id', await f.getCache({ api:'box/select',param:{status:[82,83],limit:1000},way:'post',refresh:true}) )
			
			this.setState({ formData })
		})
	}
	
	// paging
	fetch = () => $fn.fetch.call(this,'spec-case-info/index' )
	
	// 是否显示双录入按钮
	getDoubleEntry = () => {
		$http.submit(this,'spec-case-info/getDoubleEntryEnabled', { loading:false }).then((data)=>{
			this.setState({doubleEntryEnabled:data.enabled})
		})
	}
	
	// 表单
	cols = [
		{ title: '申请单条码', 		dataIndex: 'spec_code', 		...SpecCode(), 	sorter:true },
		/* 基本资料添加字段显示第三方条码 2021-08-16  --耿琰 */
		{ title: '第三方条码', 		dataIndex: 'third_spec_code', 	width:120 },
		{ title: '审核状态', 		dataIndex: 'status', 			...$fn.table.status,	render: text => $fn.getState(auditStatus,text) },
		{ title: '受检人姓名', 		dataIndex: 'patient_name', 		...$fn.table.name },
		{ title: '性别', 			dataIndex: 'sex_name', 			...$fn.table.sex },
		{ title: '年龄', 			dataIndex: 'age', 				...$fn.table.age },
		{ title: '受检人电话', 		dataIndex: 'patient_phone', 	...$fn.table.phone },
		{ title: '证件类型', 		dataIndex: 'card_type_name', 	...$fn.table.card_type },
		{ title: '证件号', 			dataIndex: 'card_no', 			...$fn.table.idcard },
		{ title: '送检单位', 		dataIndex: 'hosp_name', 		width:180 },
		{ title: '送检科室', 		dataIndex: 'department_name', 	width:180 },
		{ title: '自然项目', 		dataIndex: 'parent_kind_name', 	width:280 },
		{ title: '送检医生', 		dataIndex: 'doctor', 			...$fn.table.name },
		{ title: '医生电话', 		dataIndex: 'doctor_phone', 		...$fn.table.phone },
		{ title: '接收时间', 		dataIndex: 'receive_time',  	...$fn.table.time},
		{ title: '采集时间', 		dataIndex: 'coll_time',  		...$fn.table.time},
		{ title: '采样类型', 		dataIndex: 'collect_type',  		width:150,		render: text => $fn.getState(this.state.collectType,text) },
		{ title: '录入人', 			dataIndex: 'operator_name',  	...$fn.table.name},
		{ title: '录入时间', 		dataIndex: 'created_at',  		...$fn.table.time},
	]
	
	// 操作按钮
	controls = () => {
		const {selectedRows,formData} = this.state
		const rows = selectedRows[selectedRows.length-1]
		const { upimportinfo,importtest,batchaudit,exportInfo,fastentrycaseinfo,exporttmp,importInfo } = this.btn_power
		return [
			importInfo && Controls.click.call(this, '文件导入', ()=> {
				this.modal.open()
				this.getModalSelect()
				$fn.hideRows(formData,['box_id'], true)
				this.formRef.setValue({checked_spec:'1', checked_info:'1', third_open_shelf:'0', is_box_code: '0' })
			}),
			// 下载导入模板
			exporttmp && Controls.importTemplate.call(this),
			fastentrycaseinfo && Controls.pushTo.call(this, '快捷录入', `fast-entry` ),	// 快捷录入
			(+this.state.doubleEntryEnabled === 1 && this.permissions) 
				&& Controls.pushTo.call(this, '双录入', `double-entry?spec_code=${rows?rows.spec_code:''}&permissions=${this.permissions}` ),	// 双录入
			(+this.state.doubleEntryEnabled === 1 && (this.permissions==='second' || this.permissions==='double') )
				&& Controls.pushTo.call(this, '双录入纠错', `error-correction?permissions=${this.permissions}` ),		// 新增双录入纠错 2021-11-3  --马婷 
			exportInfo && Controls.exports.call(this,'spec-case-info/index',{label:'导出', code:''}),	// 导出
			batchaudit && Confirm.call(this, '批量审核', 'spec-case-info/batchpasscaseinfo', { isKeys:1, query: (keys,rows)=>{  	// 批量审核
				const data = []
				rows.map( (v,i) => {
					var specInfo= {}
					specInfo["uuid"] = v.uuid;
					specInfo["status"] = v.status;
					 data[i] = specInfo;
					 return data
				} )
				return {data: data}
			} }),
			importtest && Controls.imports.call(this, 'spec-case-info/importts2', { label:'导入到检测中心', refresh:false , op_key: 'TsCaseInfoExcel2', reconfirm: true}),
			upimportinfo && Controls.imports.call(this, 'spec-case-info/importup',{ label:'更新基本资料导入', refresh:false }),
		]
	}
	
	// 下一条数据
	nextData = (editOrAudit)=>{
		// editOrAudit  true:保存按钮 false: 审核按钮
		const status = this.searchFormRef.getName(['status'])
		let page = this.state.pag.current
		// this.index 当前选中的条码
		this.index===19 && page++	
		this.fetch({ page }).then(() => {
			switch (status) {
				case '0':	// 待完善
				    break;
				case '1':	// 待审核
				    this.index = editOrAudit ? this.index + 1 : this.index
				    break;
				case '2':	// 审核通过
				    this.index = editOrAudit ? this.index : this.index + 1
				    break;
			    default:
					this.index = this.index + 1
			        break;
			}
			const rows = this.state.data[this.index]
			this.setState({img_url:rows?.pic_path})
			if(rows){
				this.setState(({selectedKeys})=>{
					return {selectedKeys: [rows.uuid]}
				})
				this.patientDetailRef.setValue(rows.uuid)
			}
		})
		if(this.imgEditRef){this.imgEditRef.reset()}
	}
	
	render(){
		return (
			<>
				<Page title='基础资料录入' nobc controls={this.controls()}>
					{/* 搜索 */}
					{ SearchForm.call(this, {timeStr:'7-0-24',}) }
					<section className='ex fx mt5 '>
						<div className='h ex rel fv'  >
							{/* 表格 */}
							{ Table.call(this, { sort: true, wrapClassName:'mr5', onRow: ( {uuid},index )=>{
								this.patientDetailRef.setState({moreEdit:false})
								this.patientDetailRef.setValue(uuid)
								this.index = index
							}}) }
							{/* 显示图片 */}
							{ this.state.imageVisible ? 
								<ImgEdit onRef ={ref=>this.imgEditRef=ref} src={this.state.img_url} close={()=>{this.setState({imageVisible:false})}}/>:null}
						</div>
						<div className=' h fv bor1' style={{width:500, minWidth:400}}>
							{/* 病人详细信息 */}
							<PatientDetail onRef={ ref => this.patientDetailRef = ref } 
								onNext = {this.nextData}
								previewImage = {(img_url)=>{
									this.setState({img_url})
									this.setState({imageVisible:true})
								}}
								previewImageClose = {()=>this.setState({imageVisible:false})}
							/>
						</div>
					</section>
				</Page>
				{/* 文件导入弹框 */}
				{ FormModal.call(this,{ title:'文件导入', labelWidth:'s10', width:600, api:'spec-case-info/import', noOk:true, 
					btnSuffix: (
						<ImportFile 
							api			= 'spec-case-info/import' 
							btnConfig	= {{size:'middle', className:'ml20', ghost:false}}
							onQuery		= { () => {
								return this.formRef.getValue(true)
							} }
							onOk	= {()=>{
								this.fetch()
								this.modal.close()
							}}
							opt 	= {{op_key: 'CaseInfoExcel', reconfirm: true}}
						/>
					)
				}) }
			</>
		)
	}
}

export default Index